using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using ShopForWeb.Model.Basic;
using ShopForWeb.Model.DBContexts;
using ShopForWeb.Model.View;

namespace ShopForWeb.Services
{

  public class ProductService
  {
    private ShopDBContext _db;
    private IMapper _mapper;
    public ProductService(ShopDBContext db, IMapper mapper)
    {
      _db = db;
      _mapper = mapper;
    }
    //添加
    public async Task<int> AddNewAsync(Product product)
    {
      _db.Entry<Product>(product).State = EntityState.Added;
      return await _db.SaveChangesAsync();
    }
    //修改
    public async Task<int> ModifyAsync(Product product)
    {
      _db.Entry<Product>(product).State = EntityState.Modified;
      return await _db.SaveChangesAsync();
    }
    //删除
    public async Task<int> RemoveAsync(int productId)
    {
      var entity = _db.Entry<Product>(new Product()
      { ProductId = productId });
      entity.State = EntityState.Deleted;
      return await _db.SaveChangesAsync();
    }
    public async Task<Product> GetByIdAsync(long productId)
    {
      return await _db.ProductSet
      .Where(p=>p.ProductId==productId)
      .FirstAsync();
    }
    public async Task<int> ModifyStatusAsync(int productId, int StatusCode)
    {
      var entity = _db.Entry<Product>(new Product()
      {
        ProductId = productId,
        StatusCode = StatusCode
      });
      entity.Property("StatusCode").IsModified = true;
      return await _db.SaveChangesAsync();
    }
    public async Task<List<ProductView>> GetByPageAsync(int page, int size, int statusCode, string key, long[] ids)
    {
      IQueryable<Product> query = _db.ProductSet.AsNoTracking()
                                                .Include(p => p.OwnCaregory);
      if (statusCode != 0)
        query = query.Where(p => p.StatusCode == statusCode);
      if (!String.IsNullOrEmpty(key))
      {
        key = $"%{key}%";
        query = query.Where(p => EF.Functions.Like(p.ProductName, key));
      }
      if (ids != null && ids.Length != 0)
        query = query.Where(p => ids.Contains(p.CategoryId));
      query.OrderBy(p => p.ProductId)
          .Skip((page - 1) * size)
          .Take(size);
      return _mapper.Map<List<ProductView>>(await query.ToListAsync());
    }
    public async Task<int> GetTotalAsync(int statusCode, string key, long[] ids)
    {
      IQueryable<Product> query = _db.ProductSet.AsNoTracking()
                                                .Include(p => p.OwnCaregory);
      if (statusCode != 0)
        query = query.Where(p => p.StatusCode == statusCode);
      if (!String.IsNullOrEmpty(key))
      {
        key = $"%{key}%";
        query = query.Where(p => EF.Functions.Like(p.ProductName, key));
      }
      if (ids != null && ids.Length != 0)
        query = query.Where(p => ids.Contains(p.CategoryId));
        return  await query.CountAsync();
    }
    }
}
